import os
import sys
import django
import sqlite3

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_ultra_minimal')
django.setup()

# 检查数据库文件
db_path = 'dev.db'
if os.path.exists(db_path):
    print(f"数据库文件存在: {db_path}")
    
    # 连接数据库查看表
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    # 查看所有表
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    print("数据库中的表:")
    for table in tables:
        print(f"  - {table[0]}")
    
    # 检查是否有auth_user表
    if ('auth_user',) in tables:
        cursor.execute("SELECT id, username, is_superuser FROM auth_user;")
        users = cursor.fetchall()
        print("\n用户列表:")
        for user in users:
            print(f"  ID: {user[0]}, 用户名: {user[1]}, 超级用户: {user[2]}")
    else:
        print("未找到用户表，需要运行数据库迁移")
    
    conn.close()
else:
    print(f"数据库文件不存在: {db_path}")
    print("需要先运行数据库迁移")

# 尝试运行迁移
print("\n正在尝试运行数据库迁移...")
try:
    from django.core.management import execute_from_command_line
    execute_from_command_line(['manage.py', 'migrate', '--settings=settings_ultra_minimal'])
    print("数据库迁移完成")
except Exception as e:
    print(f"迁移失败: {e}")

# 再次检查并创建管理员
print("\n正在创建管理员账户...")
try:
    from django.contrib.auth.models import User
    
    username = 'admin'
    email = 'admin@mes.com'
    password = 'admin123456'
    
    if User.objects.filter(username=username).exists():
        print(f"用户 {username} 已存在")
        user = User.objects.get(username=username)
        print(f"是否为超级用户: {user.is_superuser}")
    else:
        user = User.objects.create_superuser(username, email, password)
        print(f"成功创建管理员账户: {username}")
        print(f"密码: {password}")
        print("现在可以登录管理后台了！")
        
except Exception as e:
    print(f"创建用户失败: {e}") 